package com.gitee.ice1938.module.admin.sysoption.fun;

import io.swagger.annotations.Api;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;

import com.gitee.ice1938.mvc.base.AjaxResult;

@RestController
@Api(tags="参数配置")
public class OptionRestController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(OptionRestController.class);

	@Autowired
	private OptionService optionService;
	@Autowired
	private CacheManager cacheManager;

	@RequestMapping(path="/admin/sys_option/init",method = RequestMethod.POST)
	public Map<String,Object> init() {
		Collection<String> list = cacheManager.getCacheNames();
		List<Map<String, Object>> cdata = new ArrayList<Map<String, Object>>();
		for (String item : list) {
			Cache cache = cacheManager.getCache(item);
			Object obj = cache.getNativeCache();
			if (obj instanceof javax.cache.Cache) {
				javax.cache.Cache c = (javax.cache.Cache) obj;
				Map e = new HashMap<String, Object>();
				e.put("name", item);
				e.put("size", 0);
				cdata.add(e);
			}
		}
		Map<String,Object> model = new HashMap<String, Object>();
		model.put("cacheInfo", cdata);
		List<Map<String, Object>> data = optionService.findOptions();
		model.put("options", data);
		return model;
	}

	@RequestMapping(path = "/admin/sys_option/clearcache", method = RequestMethod.POST)
	public AjaxResult clearCache() throws RestClientException, URISyntaxException {

		Collection<String> list = cacheManager.getCacheNames();
		for (String str : list) {
			Cache cache = cacheManager.getCache(str);
			cache.clear();
		}
		// 返回
		AjaxResult result = new AjaxResult("清除缓存成功!", list.size());
		return result;
	}

	@RequestMapping(path = "/admin/sys_option/save_option", method = RequestMethod.POST)
	public AjaxResult saveOption(@RequestParam("option_name") String optionName,
	        @RequestParam("option_value") String optionValue) {
		int flag = optionService.saveOption(optionName, optionValue);
		AjaxResult result = new AjaxResult("更新成功!", 200);
		if (flag == 0) {
			result = new AjaxResult("未更新数据!", 200);
		}
		return result;
	}
}
